package drds.server.execute_engine.data_handling.tmp;

import java.util.Collections;
import java.util.List;

import drds.server.execute_engine.data_handling.OrderByColum;
import drds.server.execute_engine.data_handling.RowDataPacketSorter;
import drds.server.net.packet.RowDataPacket;

public class RowDataSorter extends RowDataPacketSorter {

	// 记录总数(=offset+limit)
	private volatile int total;
	// 查询的记录数(=limit)
	private volatile int size;
	// 堆
	private volatile Heap heap;
	// 多列比较器
	private volatile RowDataComparator rowDataComparator;
	// 是否执行过buildHeap
	private volatile boolean hasBuild;

	public RowDataSorter(OrderByColum[] orderByColums) {
		super(orderByColums);
		this.rowDataComparator = new RowDataComparator(orderByColums);
	}

	public synchronized void setLimit(int start, int size) {
		// 容错处理
		if (start < 0) {
			start = 0;
		}
		if (size <= 0) {
			this.total = this.size = Integer.MAX_VALUE;
		} else {
			this.total = start + size;
			this.size = size;
		}
		// 统一采用顺序，order by 条件交给比较器去处理
		this.heap = new MaxHeap(rowDataComparator, total);
	}

	@Override
	public synchronized boolean addRowDataPacket(RowDataPacket rowDataPacket) {
		if (heap.getRowDataPacketList().size() < total) {
			heap.add(rowDataPacket);
			return true;
		}
		// 堆已满，构建最大堆，并执行淘汰元素逻辑
		if (heap.getRowDataPacketList().size() == total && hasBuild == false) {
			heap.buildHeap();
			hasBuild = true;
		}
		return heap.addIfRequired(rowDataPacket);
	}

	@Override
	public List<RowDataPacket> getSortedRowDataPacketList() {
		final List<RowDataPacket> rowDataPacketList = heap.getRowDataPacketList();
		if (rowDataPacketList.size() < 2) {
			return rowDataPacketList;
		}

		if (total - size > rowDataPacketList.size()) {
			return Collections.emptyList();
		}

		// 构建最大堆并排序
		if (!hasBuild) {
			heap.buildHeap();
		}
		heap.heapSort(this.size);
		return heap.getRowDataPacketList();
	}

	public RowDataComparator getRowDataComparator() {
		return rowDataComparator;
	}

}
